"""
提示词管理器 - 统一管理所有提示词模板
"""
import os
from typing import Dict, Any


class PromptManager:
    """提示词管理器 - 单例模式"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.prompts_dir = "prompts/templates"
            self.prompts_cache = {}
            self._initialized = True
    
    def load_prompt(self, prompt_name: str) -> str:
        """加载提示词模板"""
        if prompt_name in self.prompts_cache:
            return self.prompts_cache[prompt_name]
        
        prompt_file = os.path.join(self.prompts_dir, f"{prompt_name}.txt")
        
        try:
            with open(prompt_file, 'r', encoding='utf-8') as f:
                content = f.read().strip()
                self.prompts_cache[prompt_name] = content
                return content
        except FileNotFoundError:
            print(f"提示词文件未找到: {prompt_file}")
            return self._get_default_prompt(prompt_name)
        except Exception as e:
            print(f"加载提示词失败: {e}")
            return self._get_default_prompt(prompt_name)
    
    def _get_default_prompt(self, prompt_name: str) -> str:
        """获取默认提示词（备用）"""
        defaults = {
            "analysis_system": "你是一个专业的报表分析专家，负责分析用户需求并生成SQL查询。",
            "chart_system": "你是一个专业的数据可视化专家，负责根据数据生成ECharts图表。",
            "table_selection": "请分析用户需求并选择相关的数据库表。",
            "sql_generation": "请根据用户需求和表结构生成SQL查询语句。",
            "chart_generation": "请根据查询结果生成完整的HTML报告。"
        }
        return defaults.get(prompt_name, f"默认提示词: {prompt_name}")
    
    def format_prompt(self, prompt_name: str, **kwargs) -> str:
        """格式化提示词模板"""
        template = self.load_prompt(prompt_name)
        try:
            return template.format(**kwargs)
        except KeyError as e:
            print(f"提示词模板缺少参数: {e}")
            return template
        except Exception as e:
            print(f"格式化提示词失败: {e}")
            return template


# 全局单例实例
prompt_manager = PromptManager()